package com.ruoyi.business.controller;

import com.ruoyi.business.domain.DefinitionDetail;
import com.ruoyi.business.service.IDefinitionDetailService;
import com.ruoyi.business.service.IProcessService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 流程定义明细Controller
 * 
 * @author wolfcode
 * @date 2021-07-19
 */
@Controller
@RequestMapping("/business/definitionDetail")
public class DefinitionDetailController extends BaseController
{
    private String prefix = "business/definitionDetail";
    // 部署允许的后缀名
    private static final String[] activitiSuffix = {"bpmn","png","zip"};

    @Autowired
    private IDefinitionDetailService definitionDetailService;
    @Autowired
    private IProcessService processService;

    @RequiresPermissions("business:definitionDetail:view")
    @GetMapping("/{definitionId}")
    public String definitionDetail(@PathVariable("definitionId") String definitionId, ModelMap modelMap)
    {
        modelMap.put("definitionId",definitionId);
        return prefix + "/definitionDetail";
    }

    /**
     * 查询流程定义明细列表
     */
    @RequiresPermissions("business:definitionDetail:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(DefinitionDetail definitionDetail)
    {
        startPage();
        List<DefinitionDetail> list = definitionDetailService.selectDefinitionDetailList(definitionDetail);
        return getDataTable(list);
    }

    @RequiresPermissions("business:definitionDetail:upload")
    @PostMapping("/upload")
    @Log(title = "流程定义明细", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult upload(@RequestParam("processDefinition") MultipartFile file, Long definitionId){

        // 判断上传文件的后缀名,activiti支持把bpmn和png打包成zip,支持直接部署zip格式的文件
        String suffix = Optional.ofNullable(file).map(MultipartFile::getOriginalFilename)
                .map(x -> x.substring(x.lastIndexOf(".")+1)).orElse("fileEmpty");

        if (FileUploadUtils.isAllowedExtension(suffix,activitiSuffix)) {
            try {
                String fileName = FileUploadUtils.upload(file);
                String filePath = RuoYiConfig.getProfile() + fileName.substring(Constants.RESOURCE_PREFIX.length() + 1);
                // 为什么要传definitionId
                definitionDetailService.deployProcessDefinition(definitionId,filePath);
            } catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.error("部署异常,请联系管理员");
            }
        }else {
            return AjaxResult.error("文件格式只能是"+ Arrays.toString(activitiSuffix));
        }

        return AjaxResult.success();
    }

    @RequiresPermissions("business:definitionDetail:list")
    @RequestMapping("/readResource")
    @ResponseBody
    public void readResource(String deployId, String type, HttpServletResponse response) throws IOException {
        InputStream in = null;
        if ("xml".equalsIgnoreCase(type)){
            in = processService.getBpmnInputStream(deployId);
        }else if ("png".equalsIgnoreCase(type)){
            in = processService.getPngInputStream(deployId, Collections.EMPTY_LIST,Collections.EMPTY_LIST);
        }

        IOUtils.copy(in,response.getOutputStream());
    }

}
